package com.central.apps.handler;

import cn.hutool.core.map.MapUtil;
import com.central.app.common.util.BLuntil;
import com.central.app.service.HandlerService;
import com.central.apps.handler.base.LvBaseHandler;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

//车间检修计划
@Component
public class workshopfixplanHandler extends LvBaseHandler {
    @Autowired
    private HandlerService handlerService;

    @Override
    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {

        // 新增检修计划时 自动生成检修计划描述
        if (!isUpdate) { // 判断是否新增，新增时赋予描述信息

            String desc = MapUtils.getString(data, "deptEnity_fullname") + MapUtils.getString(data, "year") + "年" + MapUtils.getString(data, "month") + "月检修计划";
            data.put("plandesc", desc);
        }

        super.beforSave(app, objName, data, isUpdate);
    }

    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        if ("bl_planitems".equals(objName)) {//子表
            String assetnums = MapUtils.getString(data, "equipmentnum");//获取设备编号
            String id = MapUtils.getString(data, "id");
            if (assetnums.contains(",")) {
                String[] assetnum = assetnums.split(",");
                for (int i = 0; i < assetnum.length; i++) {
                    String num = assetnum[i];
                    String sql = " INSERT INTO bl_planitems(equipmentnum, assetnums,isfinish, fixunit, plannum, updatetime, createuser, fixtype, finishdate, " +
                            " item, plandate, createtime, reason, fixpeople, fixtext, actualhours, deptcode, version, updateuser, status, " +
                            " checkpeople, planhours,   equipmentname, createuserdesc, actualdate, wonum, planno, flag)  " +
                            " (select '" + num + "'as equipmentnum , assetnums,isfinish, fixunit, plannum, updatetime, createuser, fixtype, finishdate,  " +
                            " item, plandate, createtime, reason, fixpeople, fixtext, actualhours, deptcode, version, updateuser,  " +
                            " status, checkpeople, planhours, (select  equipmentdescribe from bl_ASSET WHERE ASSETNUM='" + num + "') as equipmentname, " +
                            "  createuserdesc, actualdate, wonum, planno, flag  " +
                            " from bl_planitems where id='" + id + "');";
                    handlerService.updateBySql(sql);
                }
                handlerService.updateBySql("delete from bl_planitems where id='" + id + "'");
            }
        }

        super.afterSave(app, objName, data, isUpdate);
    }

    /**
     * 车间检修计划设置节点自定义审批人
     *
     * @param app
     * @param id
     * @param flowNode
     * @param vars
     * @return
     * @throws Exception
     */
    public String addFlowCandidate(String app, Long id, FlowNode flowNode, Map<String, Object> vars) throws Exception {
        String executer = null;
        List<Map<String, Object>> defectreport = handlerService.findBySql("select deptcode from bl_fixplan where id=" + id);
        //拿到deptcode
        String deptcode = MapUtil.getStr(defectreport.get(0), "deptcode");
        //设备科长节点
        if (flowNode.getId().equals("hzry")) {
            List<Map<String, Object>> persons = handlerService.findBySql("select u.username from bl_person p left join sys_user u on p.personid = u.worknumber where LEFT(p.deptcode,6)= LEFT('" + deptcode + "',6)" +
                    " and position like '%设备科长%' ");
            if (CollectionUtils.isNotEmpty(persons)) {
                //人员以逗号隔开
                StringJoiner sj = new StringJoiner(",", "", "");
                for (Map<String, Object> username : persons) {
                    sj.add(MapUtils.getString(username, "username"));
                }
                executer = sj.toString();

            }

        }
//        //车间点检员节点
//        else if (flowNode.getId().equals("cjdjy")) {
//            List<Map<String, Object>> persons = handlerService.findBySql("select u.username from bl_person p left join sys_user u on p.personid = u.worknumber where LEFT(p.deptcode,6)= LEFT('" + deptcode + "',6)" +
//                    " and position like '%车间主任%' ");
//            if (CollectionUtils.isNotEmpty(persons)) {
//                //人员以逗号隔开
//                StringJoiner sj = new StringJoiner(",", "", "");
//                for (Map<String, Object> username : persons) {
//                    sj.add(MapUtils.getString(username, "username"));
//                }
//                executer = sj.toString();
//
//            }
//        }

        return executer;
    }

    @Override
    public void afterExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op, String event) throws Exception {
        if ("workshopfixplanApp".equals(app)) {
            //检修计划下的所有车间检修计划提交完成后，将检修计划的状态置为关闭
            if ("cjdjy".equals(flowNode.getId())) {//车间点检员节点
                boolean flag = op.isFlag();//判断是否审核通过
                if (flag) {
                    List<Map<String, Object>> map = handlerService.findBySql("select * from bl_fixplan where fixtype='车间检修计划' and id='"+id+"'");
//                    Map<String, Object> map = handlerService.findMainById(app, "bl_fixplan", id);//获取车间检修计划主对象
//                    String plannum = MapUtils.getString(map, "plannum");//获取车间检修计划的编号
                    String plannum = MapUtils.getString(map.get(0), "plannum");//获取车间检修计划的编号
                    //获取检修计划的编号
                    List<Map<String, Object>> fixplanTaskList=handlerService.findBySql("SELECT   DISTINCT planno from bl_planitems WHERE plannum='"+plannum+"'");
                    String num=MapUtils.getString(fixplanTaskList.get(0),"planno");

                    //根据车间检修计划编号查询车间检修计划的状态
                    //获取到汇总检修计划子表中所有车间检修计划的编号
                    List<Map<String, Object>> planTaskList = handlerService.findBySql("SELECT DISTINCT plannum,status from bl_fixplan WHERE plannum in (SELECT   DISTINCT planno from bl_planitems WHERE plannum='" + plannum + "')");
                    //判断查询回来的字段是否有值

                    if (planTaskList.size() > 0) {
                        boolean finsh=true;

                        for (int i = 0; i < planTaskList.size(); i++) {
                            //获取到状态
                            String status = MapUtils.getString(planTaskList.get(i), "status");
                            //如果状态是完成的话，就将汇总的检修计划状态置为关闭
                            if (!"完成".equals(status)) {
                                finsh=false;
                            }

                        }
                        if (finsh) {
                            handlerService.updateBySql("UPDATE bl_fixplan set status='关闭' where plannum='"+num+"'");

                        }
                    }

                }
            }

        }
        super.afterExcuteFlow(app, id, flowNode, op, event);
    }

    @Override
    public String validateFlowApproval(String app, Long id, FlowNode flowNode) throws Exception {
        if ("workshopfixplanApp".equals(app)) {//判断是否为车间检修计划
            if ("cjdjy".equals(flowNode.getId())) {//点检员节点
                //判断检修计划是否审核通过
                List<Map<String, Object>> list = handlerService.findBySql(
                        "select *from bl_fixplan where id=" + id);
                String status = MapUtils.getString(list.get(0), "status");
                if (!"已核准".equals(status)) {
                    return "检修计划未审核完成";
                }
            }
        }
        return super.validateFlowApproval(app, id, flowNode);
    }
    @Override
    public Object operate(String app, String type, Map<String, Object> params) throws Exception {
        if ("getWorkShopFixPlanLine".equals(type)) {//获取车间检修计划行信息
            String fixplannum = MapUtils.getString(params, "fixplannum"); //获取页面参数 ， 车间检修计划编号
            if(fixplannum != null && !"".equalsIgnoreCase(fixplannum)){
                //根据车间检修计划的编号去查询子表的相关信息，查询条件需带有choiceflag为空
               // handlerService.findBySql("select * from bl_planitems where isfinish<>'完成' and  choiceflag is null and plannum='"+fixplannum+"'");
                return BLuntil.toPage(params, handlerService,"select * from bl_planitems where isfinish<>'完成' and  choiceflag is null and plannum='"+fixplannum+"'");
            }

        }
        if ("fixPeople".equalsIgnoreCase(type)) {//车间检修计划维修负责人和验收负责人接口
            //拿到deptcode
            String deptcode= MapUtils.getString(params,"deptcode");
            String username= BLuntil.getParameter(params,"username");
            String nickname= BLuntil.getParameter(params,"nickname");

            String sql="select * from sys_user where LEFT(deptcode,6)=LEFT('"+deptcode+"',6)  and username  like '%"+username+"%'  and nickname  like '%"+nickname+"%'";
            return BLuntil.toPage(params,handlerService,sql);
        }
        return super.operate(app, type, params);
    }

}
